package com.zh.note.utils;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;

/**
 * @Author: zhanghuan
 * @date: 2023/5/9 22:03
 * @description: 清除敏感信息
 */
public class ClearSensitiveInfosUtil {


    public static void clearKey(String key) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        try {
            Field valueField = String.class.getDeclaredField("value");
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                valueField.setAccessible(true);
                return null;
            });
            char[] value = (char[]) valueField.get(key);
            clearArray(value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static void clearArray(char[] value) {
        if (value == null && value.length == 0) {
            return;
        }
        Arrays.fill(value, (char) 0);
    }
}
